package cn.school.ctrl;

import cn.school.entity.Page;
import cn.school.entity.Student;
import cn.school.service.GradeService;
import cn.school.service.StudentService;
import cn.school.util.LogUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.propertyeditors.CustomDateEditor;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.validation.BindingResult;
import org.springframework.validation.FieldError;
import org.springframework.web.bind.WebDataBinder;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;

import javax.servlet.http.HttpServletRequest;
import javax.validation.Valid;
import java.io.File;
import java.io.IOException;
import java.text.SimpleDateFormat;
import  java.util.*;
@Controller
public class StudentController {
    @Autowired
    private StudentService studentService;

    @Autowired
    private GradeService gradeService;


    //ModelMAp:传值给jsp
    //ModelAttribute把值放入request上下文
    @GetMapping("studentServlet")
    public String search(ModelMap map,
                         @RequestParam(value = "sname",required = false) String sname,
                         @RequestParam(value = "qq",required = false)String qq,
                         @RequestParam(value =  "wechat",required = false)String wechat,
                         @RequestParam(value =  "dateStart",required = false)Date start,
                         @RequestParam(value =  "dateEnd",required = false)Date end,
                         @RequestParam(value = "p",defaultValue = "1") int pageNo, @RequestParam(value = "pageSize",defaultValue = "10") int pageSize){
        Map<String,Object> params=new HashMap<>();
        params.put("sname",sname);
        params.put("qq",qq);
        params.put("wechat",wechat);
        params.put("dateStart",start);
        params.put("dateEnd",end);
        Page<Student> page = studentService.search(params, pageNo, pageSize);
        map.addAttribute("pages",page);

        map.addAttribute("sname",sname);
        map.addAttribute("qq",qq);
        map.addAttribute("wechat",wechat);
        map.addAttribute("dateStart",start);
        map.addAttribute("dateEnd",end);
        return "student";
    }
    //返回ajax
    @GetMapping("studentAjax")
    @ResponseBody
    public Page<Student> search2(
                         @RequestParam(value = "sname",required = false) String sname,
                         @RequestParam(value = "qq",required = false)String qq,
                         @RequestParam(value =  "wechat",required = false)String wechat,
                         @RequestParam(value =  "dateStart",required = false)Date start,
                         @RequestParam(value =  "dateEnd",required = false)Date end,
                         @RequestParam(value = "p",defaultValue = "1") int pageNo, @RequestParam(value = "pageSize",defaultValue = "10") int pageSize){
        Map<String,Object> params=new HashMap<>();
        params.put("sname",sname);
        params.put("qq",qq);
        params.put("wechat",wechat);
        params.put("dateStart",start);
        params.put("dateEnd",end);
        Page<Student> page = studentService.search(params, pageNo, pageSize);

        return page;
    }

    @RequestMapping("toAddstudent")
    public String toAdd(ModelMap map){
        //map.addAttribute("grades",gradeService.findALL());
        return "addstudent";
    }
//    @PostMapping("doAddStudent")
//    public String add( Student stu,@RequestParam(name="f_idcardpic",required = false) MultipartFile pic,HttpServletRequest request, RedirectAttributes model){
//
//        //没有限制文件的类型
//        //>>>pic.getName()
//
//        if(pic.isEmpty()==false){
//            String oldName=pic.getOriginalFilename();
//            String houzhui=oldName.substring(oldName.lastIndexOf('.'));
//            String newName=UUID.randomUUID()+houzhui;
//
//            String path=request.getServletContext().getRealPath("images");
//            File folder=new File(path);
//            if(folder.exists()==false)
//                folder.mkdirs();
//            try {
//                pic.transferTo(new File(folder,newName));
//                stu.setIdcardpic(newName);
//            } catch (IOException e) {
//                e.printStackTrace();
//                throw new RuntimeException(e);
//            }
//        }
//
//        this.studentService.add(stu);
//        model.addFlashAttribute("msg","新增成功");
//        return "redirect:studentServlet";
//    }

    @PostMapping("doAddStudent")
    public String add(@Valid Student stu, BindingResult b, @RequestParam(name="f_idcardpic",required = false) MultipartFile pic, HttpServletRequest request, RedirectAttributes model){
        if(b.hasErrors()){
            List<FieldError> ls=b.getFieldErrors();
            for (FieldError e:ls) {
                request.setAttribute(e.getField(), e.getDefaultMessage());
            }
            return "forward:toAddstudent";
        }
        //没有限制文件的类型
        //>>>pic.getName()

        if(pic.isEmpty()==false){
            String oldName=pic.getOriginalFilename();
            String houzhui=oldName.substring(oldName.lastIndexOf('.'));
            String newName=UUID.randomUUID()+houzhui;

            String path=request.getServletContext().getRealPath("images");
            File folder=new File(path);
            if(folder.exists()==false)
                folder.mkdirs();
            try {
                pic.transferTo(new File(folder,newName));
                stu.setIdcardpic(newName);
            } catch (IOException e) {
                e.printStackTrace();
                throw new RuntimeException(e);
            }
        }

        this.studentService.add(stu);
        model.addFlashAttribute("msg","新增成功");
        return "redirect:studentServlet";
    }

    @GetMapping("showStudent/{stuno}")
    public String show(@PathVariable int  stuno,ModelMap m){
       m.addAttribute("stu", this.studentService.get(stuno));
       return "showstu";
    }
    //验证手机号是否重复
    @RequestMapping("checkphone")
    @ResponseBody//把结果直接返回
    public boolean checkPhone(@RequestParam("phone") String phone){
        boolean repeat=this.studentService.checkPhoneRepeat(phone);

        return repeat;
    }
/*    public void checkPhone(@RequestParam("phone") String phone, HttpServletResponse resp){
        boolean repeat=this.studentService.checkPhoneRepeat(phone);

        resp.setContentType("application/json;charset=utf-8");
        try {
            resp.getWriter().print(repeat);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }*/

    @ExceptionHandler//只能处理本类的异常
    public String error(Exception e){
        LogUtil.error(e.getMessage(),e);
        return "error";
    }

    //DateTimeformat
    @InitBinder//本类
    public void init(WebDataBinder web){
        SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd");
        dateFormat.setLenient(false);
        web.registerCustomEditor(Date.class, new CustomDateEditor(dateFormat, true));   //true:允许输入空值，false:不能为空值
    }
}
